package com.hctforgreen.greenservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.HandlerThread;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.DbExamController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.AttrEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.ui.adapter.FuzzySearchBooksListAdapter;
import com.hctforgreen.greenservice.ui.widget.ExamineTypeListPopupView;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

import java.util.List;

/**
 * 考试试题搜索页
 * 
 * @author dhb
 * 
 */
public class ExamSearchActivity extends ParentActivity {
	public static final String FRESH_EXAMINE_NUM_ACTION = "fresh_examine_num_action";

	private FreshExaminNumReceiver mFreshExaminNumReceiver;

	/**
	 * 试卷大类型
	 */
	private ExamineTypeListPopupView mTypeListPopupView;
	private AttrEntity mCurrentFirstEntity;// 试卷类别
	/**
	 * 试卷小类型
	 */
	private ExamineTypeListPopupView mChildTypeListPopupView;
	private AttrEntity mCurrentSecondEntity;

	private ExamSearchActivity mSelf;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_examination);

		mSelf = this;
		initSkinLayout();
		initFreshExaminNumReceiver();
		initTitleButtonBar();
		initTvExamHistory();
		initWindow();
		initClickEdgehide();

	}

	/**
	 * 初始化我的考试记录数目
	 */
	private void initTvExamHistory() {
		final TextView tvHistoryNum = (TextView) findViewById(R.id.tv_exam_history);
		findViewById(R.id.lyt_exam_history).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ExamSearchActivity.this,
								ExamHistoryListActivity.class);
						startActivity(intent);
					}
				});
		new HandlerThread("getHistoryNum") {
			public void run() {

				LoginResultEntity loginResultEntity = LoginResultStoreUtil
						.get(mSelf);

				String personId = loginResultEntity.personId;
				DbExamController examController = new DbExamController(mSelf);
				final int num = examController.getExamPaperCount(personId);

				HctController controller = new HctController(
						ExamSearchActivity.this);
				try {
					final HctResult hctResult = controller
							.getPersonRecordNum(loginResultEntity.personId);
					if (hctResult != null) {
						runOnUiThread(new Runnable() {
							public void run() {
								int netNum = Integer.valueOf(hctResult.data
										+ "");
								netNum += num;
								tvHistoryNum.setText(String.valueOf(netNum));
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							tvHistoryNum.setText(num + "");
						}
					});
				}
			};
		}.start();

	}

	/**
	 * 点击边缘隐藏
	 */
	private void initClickEdgehide() {
		LinearLayout parentLyt = (LinearLayout) findViewById(R.id.lyt_parent);
		parentLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setTopLayoutVisible();
				// KeyboardUtil keyboardUtil = new KeyboardUtil();
				KeyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	private boolean setTopLayoutVisible() {
		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		if (topLyt.getVisibility() == View.GONE) {
			topLyt.setVisibility(View.VISIBLE);
			clearFocus();
			return true;
		}
		clearFocus();
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setTopLayoutVisible()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.train_examine));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
			}
		});
	}

	private void initWindow() {
		initLearningTypePopupView();
		initChildTypeListPopupView();
		initSearchBtn();
	}

	/**
	 * 初始化资料类别
	 */
	private void initLearningTypePopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void showListPopupView(View v) {
				initListPopupView();
				mTypeListPopupView.showAsDropDown(v);
			}

			private void initListPopupView() {
				mTypeListPopupView = new ExamineTypeListPopupView(
						ExamSearchActivity.this, mCurrentFirstEntity, mSelf, 0,
						null);
			}
		});
	}

	private void initChildTypeListPopupView() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		seriesBooksBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void initListPopupView() {
				if (mCurrentFirstEntity == null) {
					Toast.makeText(mSelf,
							getString(R.string.learning_materials_two_hint),
							Toast.LENGTH_LONG).show();
					return;
				}
				if (mChildTypeListPopupView == null) {
					mChildTypeListPopupView = new ExamineTypeListPopupView(
							ExamSearchActivity.this, mCurrentSecondEntity,
							mSelf, 1, mCurrentFirstEntity.id);
				}

			}

			private void showListPopupView(View v) {
				initListPopupView();
				if (mChildTypeListPopupView != null) {
					mChildTypeListPopupView.showAsDropDown(v);
				}

			}
		});
	}

	// public void initSerieEntity(SerieEntity currentFirstEntity) {
	// mCurrentFirstEntity = currentFirstEntity;
	// }

	/**
	 * 小类别名称
	 */
	public void initChildTypeBtn(AttrEntity currentFirstEntity) {
		if (currentFirstEntity == null) {
			return;
		}
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		seriesBooksBtn.setText(currentFirstEntity.name);
	}

	public void initStudyTypeEntity(AttrEntity currentFirstEntity) {
		mCurrentFirstEntity = currentFirstEntity;
	}

	public void initStudyChildTypeEntity(AttrEntity currentSecondEntity) {
		mCurrentSecondEntity = currentSecondEntity;
	}

	public void initStudyTypeBtn(AttrEntity currentSecondEntity) {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_series);
		childSeriesBooksBtn.setText(currentSecondEntity.name);
	}

	public void setFocusable(boolean bCanFocus) {
		// final EditText inputEt = (EditText) findViewById(R.id.et_input);
		// inputEt.setFocusable(bCanFocus);
		// inputEt.setFocusableInTouchMode(bCanFocus);
	}

	/**
	 * 清除小类别已选择值
	 */
	public void clearChildTypeBtn() {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText("");
		mCurrentSecondEntity = null;
		mChildTypeListPopupView = null;
	}

	private void initFuzzySearchEt() {

		final LinearLayout topLyt = (LinearLayout) findViewById(R.id.lyt_top);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		inputEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// if (!hasFocus) {
				// topLyt.setVisibility(View.VISIBLE);
				// } else if (hasFocus) {
				// if(!canDoFuzzySearch()){
				//
				// return;
				// }
				// topLyt.setVisibility(View.GONE);
				//
				// }

			}

			private boolean canDoFuzzySearch() {
				final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
				if (!childSeriesBooksBtn.getText().equals("")) {
					return true;
				} else {
					return false;
				}
			}
		});

	}

	/**
	 * 初始化搜索框
	 */

	private void initSearchBtn() {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		final EditText inputEt = (EditText) findViewById(R.id.et_input);
		final Button searchBtn = (Button) findViewById(R.id.btn_search);
		searchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (seriesBooksBtn.getText().toString().equals("")) {
					Toast.makeText(ExamSearchActivity.this,
							R.string.examination_two_hint, Toast.LENGTH_SHORT)
							.show();
					return;
				}
				// if (childSeriesBooksBtn.getText().toString().equals("")) {
				// Toast.makeText(LearningActivity.this,
				// R.string.learning_materials_three_hint,
				// Toast.LENGTH_SHORT).show();
				// return;
				// }
				setTopLayoutVisible();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				// getDbBooksUseChildSeriesId(mCurrentFirstEntity,
				// mCurrentSecondEntity, inputEt.getText().toString()
				// .trim());

				Intent intent = new Intent(ExamSearchActivity.this,
						ExamListActivity.class);
				intent.putExtra("moduleId", mCurrentFirstEntity.id);
				String childtypeId = mCurrentSecondEntity == null ? ""
						: mCurrentSecondEntity.id;
				intent.putExtra("childtypeId", childtypeId);
				intent.putExtra("searchKey", inputEt.getText().toString());
				startActivity(intent);
			}
		});
	}

	/*
	 * private void fuzzySearchBookList(ChildSerieEntity currentSecondEntity,
	 * final String keyWord) { final View fuzzySearchLyt =
	 * findViewById(R.id.lyt_fuzzy_search); final LinearLayout emptyLyt =
	 * (LinearLayout) findViewById(R.id.lyt_default_list_empty);
	 * 
	 * fuzzySearchLyt.setVisibility(View.VISIBLE); if(keyWord.equals("")){
	 * if(currentSecondEntity != null && currentSecondEntity.dataList != null &&
	 * currentSecondEntity.dataList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE);
	 * 
	 * initFuzzySearchLv(fuzzySearchLyt, currentSecondEntity.dataList); }else
	 * if(currentSecondEntity == null || currentSecondEntity.dataList == null ||
	 * currentSecondEntity.dataList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }else if(!keyWord.equals("")){
	 * 
	 * List<BookEntity> bookList = null; for(BookEntity bean :
	 * currentSecondEntity.dataList){
	 * 
	 * if(bean.displayName.contains(keyWord)){
	 * 
	 * if(bookList == null){ bookList = new ArrayList<BookEntity>(); }
	 * bookList.add(bean); }
	 * 
	 * } if(bookList != null && bookList.size() > 0){
	 * emptyLyt.setVisibility(View.GONE); initFuzzySearchLv(fuzzySearchLyt,
	 * bookList); }else if(bookList == null || bookList.size() == 0){ //
	 * fuzzySearchLyt.setVisibility(View.GONE);
	 * emptyLyt.setVisibility(View.VISIBLE); }
	 * 
	 * }
	 * 
	 * }
	 */
	private void initFuzzySearchLv(final View fuzzySearchLyt,
			ListView fuzzySearchLV, final List<BookEntity> dataList) {

		new FuzzySearchBooksListAdapter(ExamSearchActivity.this, fuzzySearchLV,
				dataList);

		fuzzySearchLV.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final BookEntity entity = (BookEntity) dataList.get(position);
				EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
				try {
					if (catalogUtil.startEntryCatalogActivity(
							ExamSearchActivity.this, entity, true)) {
						setTopLayoutVisible();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	private void clearFocus() {

		/**
		 * 使用EditText左侧的ImageView抢Focus
		 */
		View requestFocusTv = (View) findViewById(R.id.iv_request_focus);
		requestFocusTv.requestFocus();

		final EditText searchInputEt = (EditText) findViewById(R.id.et_input);
		searchInputEt.clearFocus();
	}

	/**
	 * 刷新考试记录
	 * 
	 * @author denghb
	 * 
	 */
	class FreshExaminNumReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			initTvExamHistory();
		}
	}

	private void initFreshExaminNumReceiver() {
		mFreshExaminNumReceiver = new FreshExaminNumReceiver();
		IntentFilter filter = new IntentFilter(FRESH_EXAMINE_NUM_ACTION);
		registerReceiver(mFreshExaminNumReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		if (mFreshExaminNumReceiver != null) {
			unregisterReceiver(mFreshExaminNumReceiver);
		}
		super.onDestroy();
	}

}
